﻿using Sgr.AuditLogs.Model;
using Sgr.AuditLogs.Services;
using Sgr.Caching.Services;
using Sgr.OmniMetrics;
using Sgr.OmniMetrics.Services;
using Sgr.UPMS.Application.Services;
using Sgr.Workspace.Models;
using Sgr.Workspace.ViewModels;
using System.Globalization;
using System.Threading;

namespace Sgr.Workspace.Services.Impl
{
    public class AppAnalysisService : IAppAnalysisService
    {
        internal const string APP_ENTERPRISE_USER_SUMMARY_KEY = "Sgr.Upms.EnterpriseUserSummary";        // 服务对象统计
        internal const string APP_DAILY_ACTIVITY_SUMMARY_KEY = "Sgr.Upms.DailyActivitySummary";        // 日活统计
        internal const string APP_OPERATION_SUMMARY_KEY = "Sgr.AuditLog.AppOperationSummary";        // 操作审计统计

        internal const string CACHE_KEY_OPS_OVERVIEW = "ops_overview_viewmodel";
        internal const string CACHE_KEY_ONLINE_USER_COUNT = "wp_current_online_usercount";
        internal const string CACHE_KEY_ONLINE_USER_HISTORY = "wp_current_online_usercount_history";
        internal const string CACHE_KEY_HOURLY_ACTIVITY_TEMPLATE = "wp_hourly_activity_distribution_{0}_{1}";

        internal const int MAX_DAILY_ACTIVITY_BACKFILL_DAYS = 30;
        internal const int MAX_OPERATION_BACKFILL_DAYS = 14;
        internal const int BATCH_DELAY_INTERVAL = 3;
        internal const int BATCH_DELAY_MILLISECONDS = 100;

        private readonly IOmniMetricService _omniMetricService;
        private readonly IAuditSummaryService _auditSummaryService;
        private readonly IUpmsSummaryService _upmsSummaryService;
        private readonly ICacheManager _cacheManager;
        private readonly ILogger<AppAnalysisService> _logger;

        public AppAnalysisService(
            IOmniMetricService omniMetricService,
            IAuditSummaryService auditSummaryService,
            IUpmsSummaryService upmsSummaryService,
            ICacheManager cacheManager,
            ILogger<AppAnalysisService> logger)
        {
            _omniMetricService = omniMetricService ?? throw new ArgumentNullException(nameof(omniMetricService));
            _auditSummaryService = auditSummaryService ?? throw new ArgumentNullException(nameof(auditSummaryService));
            _upmsSummaryService = upmsSummaryService ?? throw new ArgumentNullException(nameof(upmsSummaryService));
            _cacheManager = cacheManager ?? throw new ArgumentNullException(nameof(cacheManager));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        public async Task<OpsOverviewViewModel> GetOpsOverviewAsync(CancellationToken cancellationToken = default)
        {
            var cacheOptions = _cacheManager.CreateCacheEntryOptions()
                .SetAbsoluteExpirationRelativeToNowSecond(20 * 60); // 20分钟

            // 使用缓存
            OpsOverviewViewModel? data = await _cacheManager.GetAsync(
                CACHE_KEY_OPS_OVERVIEW,
                async () =>
                {
                    OpsOverviewViewModel opsOverviewViewModel = new OpsOverviewViewModel();

                    // 获取企业用户信息
                    await GetAndSetEnterpriseUserInfo(opsOverviewViewModel, cancellationToken);

                    // 获取日活用户信息
                    await GetAndSetDailyActivityOverviewInfo(opsOverviewViewModel, cancellationToken);

                    // 操作统计
                    await GetAndSetAuditOverviewInfo(opsOverviewViewModel, cancellationToken);

                    // 活跃度分布
                    opsOverviewViewModel.HourlyActivityDistribution = await GetHourlyActivityDistributionAsync(cancellationToken);

                    return opsOverviewViewModel;
                },
                cacheOptions,
                cancellationToken);

            // 当前在线用户数
            OpsOverviewViewModel result = data ?? new OpsOverviewViewModel();
            var online = await GetCurrentOnlineUserCountAsync(cancellationToken);
            result.CurrentOnlineUserCount = online.Current;
            result.PreOnlineUserCount = online.Previous;

            return result;
        }

        #region 获取运维概况视图模型相关函数

        /// <summary>
        /// 获取企业用户信息
        /// </summary>
        /// <param name="opsOverviewViewModel"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task GetAndSetEnterpriseUserInfo(OpsOverviewViewModel opsOverviewViewModel, CancellationToken cancellationToken)
        {
            OmniMetric<EnterpriseUserInfo> enterpriseUserSummary =
                await EnsureMetricExists<EnterpriseUserInfo>(APP_ENTERPRISE_USER_SUMMARY_KEY, Granularity.Year, cancellationToken);

            opsOverviewViewModel.CurrentOrgCount = enterpriseUserSummary.ExtendedValues?.CurrentOrgCount ?? 0;
            opsOverviewViewModel.PrevOrgCount = enterpriseUserSummary.ExtendedValues?.PrevOrgCount ?? 0;
            opsOverviewViewModel.OpOrgs = enterpriseUserSummary.ExtendedValues?.OpOrgs;

            opsOverviewViewModel.CurrentUserCount = enterpriseUserSummary.ExtendedValues?.CurrentUserCount ?? 0;
            opsOverviewViewModel.PreUserCount = enterpriseUserSummary.ExtendedValues?.PreUserCount ?? 0;
            opsOverviewViewModel.OpUsers = enterpriseUserSummary.ExtendedValues?.OpUsers;
        }

        /// <summary>
        /// 获取日活用户信息
        /// </summary>
        /// <param name="opsOverviewViewModel"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task GetAndSetDailyActivityOverviewInfo(OpsOverviewViewModel opsOverviewViewModel, CancellationToken cancellationToken)
        {
            OmniMetric<DailyActivityOverviewInfo> dailyActivitySummary =
                await EnsureMetricExists<DailyActivityOverviewInfo>(APP_DAILY_ACTIVITY_SUMMARY_KEY, Granularity.Year, cancellationToken);

            if (dailyActivitySummary.ExtendedValues?.Activities != null
                && dailyActivitySummary.ExtendedValues?.Activities.Length == MAX_DAILY_ACTIVITY_BACKFILL_DAYS)
            {
                opsOverviewViewModel.Activities = dailyActivitySummary.ExtendedValues.GetActivitiesArray(30);
                opsOverviewViewModel.MaxActivityCount = (int)dailyActivitySummary.BasicValue01;
            }
        }

        /// <summary>
        /// 操作统计
        /// </summary>
        /// <param name="opsOverviewViewModel"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task GetAndSetAuditOverviewInfo(OpsOverviewViewModel opsOverviewViewModel, CancellationToken cancellationToken)
        {
            OmniMetric<AuditOverviewInfo> auditOverview =
                await EnsureMetricExists<AuditOverviewInfo>(APP_OPERATION_SUMMARY_KEY, Granularity.Year, cancellationToken);

            if (auditOverview.ExtendedValues != null
                && auditOverview.ExtendedValues.Totals.Length == MAX_OPERATION_BACKFILL_DAYS)
            {
                opsOverviewViewModel.OpTotals = auditOverview.ExtendedValues.GetRecentTotalsArray(14);
                opsOverviewViewModel.OpWeeklySuccessRate = auditOverview.ExtendedValues.GetWeeklySuccessRate();
                opsOverviewViewModel.OpSecondWeekSuccessRate = auditOverview.ExtendedValues.GetSecondWeekSuccessRate();
            }
        }

        #endregion 获取运维概况视图模型相关函数

        /// <summary>
        /// 获取近一周的小时活跃度分布
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>包含24个元素的数组，索引0代表0-1点，索引23代表23-24点的操作总数</returns>
        public async Task<int[]> GetHourlyActivityDistributionAsync(CancellationToken cancellationToken = default)
        {
            // 定义默认时间范围（最近7天）
            var endTime = DateTime.UtcNow.Date.AddDays(1); // 明天0点
            var startTime = endTime.AddDays(-7); // 7天前0点

            // 生成缓存键
            var cacheKey =
                string.Format(CACHE_KEY_HOURLY_ACTIVITY_TEMPLATE, startTime.ToString("yyyyMMdd"), endTime.ToString("yyyyMMdd"));

            // 设置缓存选项（12小时绝对过期）
            var cacheOptions = _cacheManager.CreateCacheEntryOptions()
                .SetAbsoluteExpirationRelativeToNowSecond(12 * 3600);

            // 获取缓存数据，如果不存在则从服务获取
            var result = await _cacheManager.GetAsync(
                cacheKey,
                async () =>
                {
                    try
                    {
                        return await _auditSummaryService.GetHourlyActivityDistribution(startTime, endTime, cancellationToken);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "获取小时活跃度分布数据失败，时间范围：{StartTime} 到 {EndTime}",
                                startTime, endTime);
                        return new int[24];
                    }
                },
                cacheOptions, cancellationToken);

            // 确保返回非空的24小时数组
            return result ?? new int[24];
        }

        /// <summary>
        /// 获取当前在线用户数（基于有效的刷新令牌）
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        public async Task<CurrentOnlineUserInfo> GetCurrentOnlineUserCountAsync(CancellationToken cancellationToken = default)
        {
            // 设置缓存选项（20分钟绝对过期）
            var cacheOptions = _cacheManager.CreateCacheEntryOptions()
                .SetAbsoluteExpirationRelativeToNowSecond(5 * 60);

            var result = await _cacheManager.GetAsync(
               CACHE_KEY_ONLINE_USER_COUNT,
               async () =>
               {
                   int currentCount = 0;
                   try
                   {
                       currentCount = await _upmsSummaryService.GetCurrentOnlineUserCountAsync(cancellationToken);
                   }
                   catch (Exception ex)
                   {
                       _logger.LogError(ex, "获取当前在线用户数失败");
                   }

                   var historyCacheOptions = _cacheManager.CreateCacheEntryOptions()
                       .SetAbsoluteExpiration(DateTime.UtcNow.AddDays(7));

                   var (historyExists, historyInfo) = await _cacheManager.TryGetValueAsync<CurrentOnlineUserInfo>(CACHE_KEY_ONLINE_USER_HISTORY, cancellationToken);
                   int previousCount = historyExists && historyInfo != null ? historyInfo.Current : 0;

                   var info = new CurrentOnlineUserInfo(currentCount, previousCount);

                   // 异步更新历史缓存，不阻塞主流程
                   _ = Task.Run(async () =>
                   {
                       using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(1));
                       try
                       {
                           await _cacheManager.SetAsync(CACHE_KEY_ONLINE_USER_HISTORY, info, historyCacheOptions, cts.Token);
                       }
                       catch (Exception ex)
                       {
                           _logger.LogWarning(ex, "更新在线用户历史缓存失败");
                       }
                   }, cancellationToken);

                   return info;
               },
               cacheOptions, cancellationToken);

            return result ?? new CurrentOnlineUserInfo();
        }

        public async Task AnalysisAsync(CancellationToken cancellationToken = default)
        {
            await AnalyzeOperationStatistics(cancellationToken);
            await AnalyzeDailyActivityStatistics(cancellationToken);
            await AnalyzeEnterpriseUserStatistics(cancellationToken);
        }

        private async Task<OmniMetric<T>> EnsureMetricExists<T>(
            string metricKey,
            Granularity granularity,
            CancellationToken cancellationToken = default)
            where T : class, new()
        {
            var metric = await _omniMetricService.GetLatestMetricAsync<T>(metricKey, granularity, cancellationToken);

            if (metric == null)
            {
                _logger.LogInformation("未找到指标 {MetricKey}，将初始化新指标。", metricKey);
                metric = new OmniMetric<T>
                {
                    MetricKey = metricKey,
                    TimeGranularity = granularity,
                    ExtendedValues = new T()
                };
            }

            if (metric.ExtendedValues == null)
            {
                _logger.LogInformation("指标 {MetricKey} 的扩展值为空，初始化默认值。", metricKey);
                metric.ExtendedValues = new T();
            }

            return metric;
        }

        private async Task AnalyzeEnterpriseUserStatistics(CancellationToken cancellationToken = default)
        {
            // 服务对象数量统计
            OmniMetric<EnterpriseUserInfo> enterpriseUserSummary =
                await EnsureMetricExists<EnterpriseUserInfo>(APP_ENTERPRISE_USER_SUMMARY_KEY, Granularity.Year, cancellationToken);

            if (enterpriseUserSummary.ExtendedValues == null)
                throw new Sgr.Exceptions.BusinessException("服务对象统计数据的扩展值不能为空");

            // 根据不同的统计粒度判断数据是否需要更新
            bool isDataCurrent = IsDataCurrent(Granularity.Week, enterpriseUserSummary.UpdateTime);
            if (isDataCurrent)
            {
                _logger.LogInformation("服务对象数据已是最新，上次更新：{LastUpdate}", enterpriseUserSummary.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                return;
            }

            _logger.LogInformation("开始更新服务对象统计数据，上次更新：{LastUpdate} ", enterpriseUserSummary.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss"));

            try
            {
                // 获取当前的企业和用户数量
                int currentEnterpriseCount = await _upmsSummaryService.GetTotalEnterpriseCountAsync(cancellationToken);
                int currentUserCount = await _upmsSummaryService.GetTotalUserCountAsync(cancellationToken);

                // 获取历史数据作为上一周期的数据
                var previousEnterpriseCount = enterpriseUserSummary.ExtendedValues.CurrentOrgCount;
                var previousUserCount = enterpriseUserSummary.ExtendedValues.CurrentUserCount;

                // 更新数据
                enterpriseUserSummary.ExtendedValues.SetValues(
                    currentEnterpriseCount,
                    previousEnterpriseCount,
                    currentUserCount,
                    previousUserCount);

                // 更新基础数值
                enterpriseUserSummary.BasicValue01 = currentEnterpriseCount; // 当前企业数
                enterpriseUserSummary.BasicValue02 = currentUserCount;       // 当前用户数

                // 设置时间值并对齐到统计粒度
                enterpriseUserSummary.AlignTimeValue();
                enterpriseUserSummary.UpdateTime = DateTime.UtcNow;

                // 保存指标数据
                await _omniMetricService.SaveMetricAsync(enterpriseUserSummary, cancellationToken).ConfigureAwait(false);

                _logger.LogInformation("服务对象统计数据更新完成，企业数：{EnterpriseCount}（变化：{EnterpriseChange:F2}%），用户数：{UserCount}（变化：{UserChange:F2}%）",
                    currentEnterpriseCount, enterpriseUserSummary.ExtendedValues.GetOrgChangeRate(),
                    currentUserCount, enterpriseUserSummary.ExtendedValues.GetUserChangeRate());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新服务对象统计数据时发生错误");
            }
        }

        private async Task AnalyzeDailyActivityStatistics(CancellationToken cancellationToken = default)
        {
            // 日活统计
            OmniMetric<DailyActivityOverviewInfo> dailyActivitySummary =
                await EnsureMetricExists<DailyActivityOverviewInfo>(APP_DAILY_ACTIVITY_SUMMARY_KEY, Granularity.Year, cancellationToken);

            if (dailyActivitySummary.ExtendedValues == null)
                throw new Sgr.Exceptions.BusinessException("日活统计数据的扩展值不能为空");

            var today = DateTime.UtcNow.Date;
            var lastUpdateDate = dailyActivitySummary.UpdateTime.Date;
            var daysDiff = (today - lastUpdateDate).Days;

            if (daysDiff <= 0)
            {
                _logger.LogInformation("日活数据已是最新，上次更新：{LastUpdate}", dailyActivitySummary.UpdateTime.ToString("yyyy-MM-dd"));
                return;
            }

            // 最多补30天的数据，从昨天开始往前补
            int daysToFill = Math.Min(daysDiff, MAX_DAILY_ACTIVITY_BACKFILL_DAYS);
            int successCount = 0;
            int failCount = 0;

            _logger.LogInformation("开始补填日活数据，需要处理 {Days} 天，从 {StartDate} 到 {EndDate}",
                daysToFill, today.AddDays(-daysToFill).ToString("yyyy-MM-dd"), today.AddDays(-1).ToString("yyyy-MM-dd"));

            // 从最老的日期开始补填到最新的日期
            for (int i = daysToFill; i >= 1; i--)
            {
                DateTime analysisDate = today.AddDays(-i);

                try
                {
                    var start = analysisDate.Date;
                    var end = analysisDate.Date.AddDays(1);
                    var activityUserCount = await _upmsSummaryService.GetActivityUserCount(start, end, cancellationToken);

                    _logger.LogInformation("日活数据统计日期：{Date}，日活用户：{activityUserCount}",
                       analysisDate.ToString("yyyy-MM-dd"), activityUserCount);

                    // 更新指标
                    dailyActivitySummary.ExtendedValues.UpdateData(analysisDate, activityUserCount);

                    // 最高日活用户数
                    if (dailyActivitySummary.BasicValue01 < activityUserCount)
                        dailyActivitySummary.BasicValue01 = activityUserCount;

                    successCount++;

                    // 每3天延迟一次，避免对数据库造成压力
                    if ((daysToFill - i + 1) % BATCH_DELAY_INTERVAL == 0)
                    {
                        await Task.Delay(BATCH_DELAY_MILLISECONDS, cancellationToken);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "日活数据补填数据失败，日期：{Date}", analysisDate.ToString("yyyy-MM-dd"));

                    // 补填失败时使用默认值
                    dailyActivitySummary.ExtendedValues.UpdateData(analysisDate, 0);
                    failCount++;
                }
            }

            // 只在所有数据处理完成后更新基础数值和保存一次
            if (successCount > 0 || failCount > 0)
            {
                try
                {
                    // 近七天日活均值
                    dailyActivitySummary.BasicValue02 = dailyActivitySummary.ExtendedValues.GetWeeklyAverageActivities();

                    dailyActivitySummary.AlignTimeValue();
                    dailyActivitySummary.UpdateTime = DateTime.UtcNow;
                    await _omniMetricService.SaveMetricAsync(dailyActivitySummary, cancellationToken).ConfigureAwait(false);

                    _logger.LogInformation("日活数据补填完成，成功：{Success} 天，失败：{Fail} 天", successCount, failCount);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "保存日活数据时发生错误");
                }
            }
        }

        private async Task AnalyzeOperationStatistics(CancellationToken cancellationToken = default)
        {
            // 操作统计
            OmniMetric<AuditOverviewInfo> auditOverviewPreWeek =
                await EnsureMetricExists<AuditOverviewInfo>(APP_OPERATION_SUMMARY_KEY, Granularity.Year, cancellationToken);

            if (auditOverviewPreWeek.ExtendedValues == null)
                throw new Sgr.Exceptions.BusinessException("操作审计数据的扩展值不能为空");

            var today = DateTime.UtcNow.Date;
            var lastUpdateDate = auditOverviewPreWeek.UpdateTime.Date;
            var daysDiff = (today - lastUpdateDate).Days;
            if (daysDiff <= 0)
            {
                _logger.LogInformation("操作审计数据已是最新，上次更新：{LastUpdate}", auditOverviewPreWeek.UpdateTime.ToString("yyyy-MM-dd"));
                return;
            }

            // 最多补14天的数据，从昨天开始往前补
            int daysToFill = Math.Min(daysDiff, MAX_OPERATION_BACKFILL_DAYS);
            int successCount = 0;
            int failCount = 0;

            _logger.LogInformation("开始补填操作审计数据，需要处理 {Days} 天，从 {StartDate} 到 {EndDate}",
                daysToFill, today.AddDays(-daysToFill).ToString("yyyy-MM-dd"), today.AddDays(-1).ToString("yyyy-MM-dd"));

            // 从最老的日期开始补填到最新的日期
            for (int i = daysToFill; i >= 1; i--)
            {
                DateTime analysisDate = today.AddDays(-i);

                try
                {
                    var start = analysisDate.Date;
                    var end = analysisDate.Date.AddDays(1);
                    var statistics = await _auditSummaryService.GetOperationStatistics(start, end, cancellationToken);

                    _logger.LogInformation("操作审计统计日期：{Date}，总数：{Total}，失败数：{Fail}",
                       analysisDate.ToString("yyyy-MM-dd"), statistics.TotalOperations, statistics.FailedOperations);

                    // 更新指标
                    auditOverviewPreWeek.ExtendedValues.UpdateData(analysisDate, statistics.TotalOperations, statistics.FailedOperations);
                    successCount++;

                    // 每3天延迟一次，避免对数据库造成压力
                    if ((daysToFill - i + 1) % BATCH_DELAY_INTERVAL == 0)
                    {
                        await Task.Delay(BATCH_DELAY_MILLISECONDS, cancellationToken);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "操作审计补填数据失败，日期：{Date}", analysisDate.ToString("yyyy-MM-dd"));

                    // 补填失败时使用默认值
                    auditOverviewPreWeek.ExtendedValues.UpdateData(analysisDate, 0, 0);
                    failCount++;
                }
            }

            // 只在所有数据处理完成后更新基础数值和保存一次
            if (successCount > 0 || failCount > 0)
            {
                try
                {
                    // 近七天操作总数
                    auditOverviewPreWeek.BasicValue01 = auditOverviewPreWeek.ExtendedValues.GetWeeklyTotal();
                    // 近七天操作异常数
                    auditOverviewPreWeek.BasicValue02 = auditOverviewPreWeek.ExtendedValues.GetWeeklyFailures();
                    // 近七天操作总数环比变化率（百分比）
                    auditOverviewPreWeek.BasicValue03 = auditOverviewPreWeek.ExtendedValues.GetTotalGrowthRate();

                    auditOverviewPreWeek.AlignTimeValue();
                    auditOverviewPreWeek.UpdateTime = DateTime.UtcNow;
                    await _omniMetricService.SaveMetricAsync(auditOverviewPreWeek, cancellationToken).ConfigureAwait(false);

                    _logger.LogInformation("操作审计数据补填完成，成功：{Success} 天，失败：{Fail} 天", successCount, failCount);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "保存操作审计指标数据时发生错误");
                }
            }
        }

        /// <summary>
        /// 根据统计粒度判断数据是否是最新的
        /// </summary>
        /// <param name="granularity">统计粒度</param>
        /// <param name="lastUpdateTime">上次更新时间</param>
        /// <returns>true表示数据是最新的，false表示需要更新</returns>
        private static bool IsDataCurrent(Granularity granularity, DateTime lastUpdateTime)
        {
            var now = DateTime.UtcNow;

            return granularity switch
            {
                Granularity.Minute => (now - lastUpdateTime).TotalMinutes < 1,                    // 1分钟内算最新
                Granularity.Hour => now.Hour == lastUpdateTime.Hour && now.Date == lastUpdateTime.Date, // 同一小时算最新
                Granularity.Day => now.Date == lastUpdateTime.Date,                               // 同一天算最新
                Granularity.Week => GetCalendarWeekId(now) == GetCalendarWeekId(lastUpdateTime),
                Granularity.Month => now.Month == lastUpdateTime.Month && now.Year == lastUpdateTime.Year, // 同一月算最新
                Granularity.Year => now.Year == lastUpdateTime.Year,                              // 同一年算最新
                Granularity.None => (now - lastUpdateTime).TotalHours < 1,                        // 无粒度：1小时内算最新
                _ => (now - lastUpdateTime).TotalHours < 1                                         // 默认：1小时内算最新
            };
        }

        /// <summary>
        /// 获取日期对应的ISO周ID（年+周数）
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        private static int GetCalendarWeekId(DateTime date)
        {
            var calendar = CultureInfo.InvariantCulture.Calendar;
            var year = date.Year;
            var week = calendar.GetWeekOfYear(
                date,
                CalendarWeekRule.FirstFourDayWeek,
                DayOfWeek.Monday);

            // 处理跨年周的情况
            if (week >= 52 && date.Month == 1)
                year--;
            else if (week == 1 && date.Month == 12)
                year++;

            return year * 100 + week;
        }
    }
}